import AMapLoader from "@amap/amap-jsapi-loader";
import axios from "axios";

const url = "http://192.168.9.228:9999";

export const AMapKey = AMapLoader.load({
  key: "cf14edbcdfd710141a8a42774374723d",
  version: "2.0",
});

// 通过IP地址定位
export const getCurrentCity = async () => {
  let AMap = await AMapKey;
  const localCity = JSON.parse(localStorage.getItem("HKZF_CITY"));

  if (!localCity) {
    return new Promise((resolve, reject) => {
      AMap.plugin("AMap.CitySearch", () => {
        let citysearch = new AMap.CitySearch();

        //自动获取用户IP，返回当前城市
        citysearch.getLocalCity(async (status, result) => {
          if (status === "complete") {
            try {
              const { data } = await axios.get(`${url}/area/info?name=${result.city}`);
              localStorage.setItem("HKZF_CITY", JSON.stringify(data.body));
              resolve(data.body);
            } catch (e) {
              reject(e);
            }
          } else {
            reject(result);
          }
        });
      });
    });
  } else {
    return Promise.resolve(localCity);
  }
};

export const getCityInfo = (key) => {
  let local = window.localStorage.getItem(key);
  if (local) {
    return JSON.parse(local);
  } else {
    return {};
  }
};
